<template>
  <div>
    <AForm :model="searchFrom" class="erp-search-form">
      <ARow class="grid-demo" :gutter="10">
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <AInput v-model="searchFrom.supplierName" placeholder="公司名" allow-clear />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <ARangePicker
              v-model="searchFrom.invoiceDate"
              :placeholder="['收票日期', '收票日期']"
            />
          </AFormItem>
        </ACol>
      </ARow>
    </AForm>
    <ACard>
      <div class="erp-mb-10 w100 erp-search-btn-box">
        <ASpace>
          <AButton type="primary" @click="onSearch">
            <template #icon>
              <icon-search />
            </template>
          </AButton>
          <ATooltip content="清空筛选项" position="top">
            <AButton type="dashed" @click="onReset">
              <template #icon>
                <icon-refresh />
              </template>
            </AButton>
          </ATooltip>
          <AButton v-if="isAuth([1, 3])" type="outline" @click="openEdit('新增')">新增</AButton>
        </ASpace>
        <ASpace>
          <AButton type="primary" :loading="exportLoad" @click="onExport('table')">导出</AButton>
        </ASpace>
      </div>
      <ATable
        :pagination="false"
        :data="tableData"
        :bordered="{ cell: true }"
        column-resizable
        size="small"
      >
        <template #columns>
          <ATableColumn title="客户名称" data-index="supplierName" :width="170"></ATableColumn>
          <ATableColumn title="采购单数" data-index="detailList" :width="100">
            <template #cell="{ record }">
              <div v-if="isEmpty(record.detailList)">0</div>
              <ALink v-else @click="rowEvent(record, 'open-bill')">
                {{ record.detailList.length }}
              </ALink>
            </template>
          </ATableColumn>
          <ATableColumn title="收票日期" data-index="invoiceDate" :width="180">
            <template #cell="{ record }">
              <div v-if="record.invoiceDate">
                {{ dayjs(record.invoiceDate).format('YYYY-MM-DD') }}
              </div>
            </template>
          </ATableColumn>
          <ATableColumn title="收票金额" data-index="invoiceAmt" :width="130">
            <template #cell="{ record }">
              <div>{{ `¥${formatPrice(record.invoiceAmt)}` }}</div>
            </template>
          </ATableColumn>
          <ATableColumn title="票据文件" data-index="contactName" :width="100" align="center">
            <template #cell="{ record }">
              <ADropdown
                v-if="!isEmpty(record.fileList)"
                @select="(fileUrl: any) => openFlie(record, fileUrl)"
              >
                <ALink>{{ record.fileList.length }}</ALink>
                <template #content>
                  <ADoption
                    v-for="(item, index) in record.fileList"
                    :key="index"
                    :value="item.fileUrl"
                  >
                    {{ item.fileName }}
                  </ADoption>
                </template>
              </ADropdown>
            </template>
          </ATableColumn>
          <ATableColumn title="备注" data-index="remark" :width="100" align="center">
          </ATableColumn>
          <ATableColumn title="创建时间" data-index="createdDt" :width="160" align="center">
            <template #cell="{ record }">
              <div v-if="record.createdDt">{{ dayjs(record.createdDt).format('YYYY-MM-DD') }}</div>
            </template>
          </ATableColumn>
          <ATableColumn
            v-if="isAuth([1, 3])"
            title="操作"
            :width="145"
            align="center"
            fixed="right"
          >
            <template #cell="{ record }">
              <ASpace>
                <AButton
                  v-if="record.customerName !== '汇总'"
                  type="primary"
                  size="mini"
                  @click="rowEvent(record, 'edit')"
                >
                  修改
                </AButton>
                <AButton
                  v-if="record.customerName !== '汇总'"
                  status="danger"
                  size="mini"
                  @click="rowEvent(record, 'del')"
                >
                  删除
                </AButton>
              </ASpace>
            </template>
          </ATableColumn>
        </template>
      </ATable>
      <div class="arco-table-pagination">
        <APagination
          :total="pageParam.totalCount"
          :page-size="pageParam.pageSize"
          show-total
          @change="(page: number) => tableEvent('page-change', page)"
        />
      </div>
    </ACard>
    <EditPopupForm
      v-model:visible="editModal"
      :title="editModalTitle"
      :check-data="rowData"
      @reload="getTableData"
    ></EditPopupForm>
    <!-- 采购单 -->
    <AModal
      v-model:visible="purchaseBillShow"
      title="采购单"
      width="800px"
      :body-style="{ padding: '0px' }"
      :footer="false"
    >
      <AScrollbar style="max-height: calc(100vh - 170px); overflow: auto; padding: 20px">
        <ATable
          :pagination="false"
          :data="purchaseBills"
          :bordered="{ cell: true }"
          column-resizable
          size="small"
        >
          <template #columns>
            <ATableColumn title="采购单号" data-index="relatedOrderCode" :width="100">
            </ATableColumn>
            <ATableColumn title="供应商" data-index="supplierName" :width="100"></ATableColumn>
            <ATableColumn title="产品名称" data-index="productName" :width="100"></ATableColumn>
            <ATableColumn title="规格型号" data-index="specModel" :width="100"></ATableColumn>
            <ATableColumn title="单位" data-index="unit" :width="100"></ATableColumn>
            <ATableColumn title="数量" data-index="qty" :width="100"></ATableColumn>
            <ATableColumn title="单价" data-index="unitPrice" :width="100"></ATableColumn>
            <ATableColumn title="金额" data-index="amt" :width="100">
              <template #cell="{ record }">
                {{ formatPrice(decimalRound(record.qty! * record.unitPrice!, 4)) }}
              </template>
            </ATableColumn>
            <ATableColumn title="含税" data-index="isInclTax" :width="70" align="center">
              <template #cell="{ record }">
                <icon-check-circle-fill
                  v-if="record.isInclTax"
                  style="color: #67c23a"
                  size="20px"
                />
                <icon-close-circle-fill v-if="!record.isInclTax" style="color: red" size="20px" />
              </template>
            </ATableColumn>
            <ATableColumn title="交货日期" data-index="deliveryDate" :width="120">
              <template #cell="{ record }">
                <div v-if="record.deliveryDate">
                  {{ dayjs(record.deliveryDate).format('YYYY-MM-DD') }}
                </div>
              </template>
            </ATableColumn>
          </template>
        </ATable>
      </AScrollbar>
    </AModal>
  </div>
</template>

<script lang="ts" setup>
import EditPopupForm from './editPopupForm.vue'
import dayjs from 'dayjs'
import { Message, Modal } from '@arco-design/web-vue'
import { downloadByteFile, formatPrice, decimalRound } from '@renderer/utils/mixins'
import { isEmpty } from 'lodash-es'
import { isAuth } from '@renderer/utils/auth'
import {
  delInvoice,
  getInvoiceAllList,
  getInvoicePageList,
  InvoiceListSearch,
  InvoiceResItem,
  InvoiceResItemDetailList
} from '@renderer/api/invoiceManage'

const searchFrom = ref<InvoiceListSearch>({
  supplierName: '',
  invoiceStartDate: '',
  invoiceEndDate: '',
  deliveryOrderId: '',
  createdStartDate: '',
  createdEndDate: '',
  invoiceType: 0,
  invoiceDate: [],
  createTime: []
})
const editModal = ref(false)
const editModalTitle = ref('新增')
const tableData = ref<InvoiceResItem[]>([])
const pageParam = reactive({
  currentPage: 1,
  pageSize: 20,
  totalCount: 0
})
const purchaseBillShow = ref(false)
const purchaseBills = ref<InvoiceResItemDetailList[]>([])

onMounted(() => {
  getTableData()
})

async function getTableData() {
  const [invoiceStartDate, invoiceEndDate] = searchFrom.value.invoiceDate! || []
  searchFrom.value.invoiceStartDate = invoiceStartDate
    ? dayjs(invoiceStartDate).format('YYYY-MM-DD')
    : ''
  searchFrom.value.invoiceEndDate = invoiceEndDate ? dayjs(invoiceEndDate).format('YYYY-MM-DD') : ''
  const res = await getInvoicePageList({ ...searchFrom.value, ...pageParam })
  tableData.value = res.data.list
  pageParam.totalCount = res.data.totalCount!
}

function onSearch() {
  pageParam.currentPage = 1
  getTableData()
}

function onReset() {
  searchFrom.value = {
    supplierName: '',
    invoiceStartDate: '',
    invoiceEndDate: '',
    deliveryOrderId: '',
    createdStartDate: '',
    createdEndDate: '',
    invoiceType: 0,
    invoiceDate: [],
    createTime: []
  }
  pageParam.currentPage = 1
  pageParam.pageSize = 20
  getTableData()
}

function tableEvent(type: 'page-change', param: any) {
  switch (type) {
    case 'page-change':
      pageParam.currentPage = param
      getTableData()
      break

    default:
      break
  }
}

function openEdit(title: string) {
  rowData.value = {
    invoiceId: '',
    invoiceCode: '',
    customerId: '',
    supplierName: '',
    invoiceDate: '',
    invoiceAmt: 0,
    invoiceStatus: 0,
    remark: '',
    detailList: [],
    fileList: [],
    invoiceType: 0
  }
  editModalTitle.value = title
  editModal.value = true
}

const rowData = ref<InvoiceResItem>()

function rowEvent(row: InvoiceResItem, type: string) {
  switch (type) {
    case 'del':
      Modal.warning({
        title: '警告',
        content: '当前数据删除后不可恢复，是否继续？',
        okText: '确认',
        cancelText: '取消',
        simple: false,
        hideCancel: false,
        maskClosable: false,
        closable: false,
        onOk: () => {
          delInvoice({ invoiceId: row.invoiceId }).then(() => {
            Message.success('删除成功')
            getTableData()
          })
        },
        onCancel: () => {}
      })
      break
    case 'copy':
      rowData.value = row
      editModalTitle.value = '新增'
      editModal.value = true
      break
    case 'edit':
      rowData.value = row
      editModalTitle.value = '修改'
      editModal.value = true
      break
    case 'open-bill':
      purchaseBills.value = row.detailList
      purchaseBillShow.value = true
      break

    default:
      break
  }
}

const openFlie = (record: InvoiceResItem, flieUrl: any) => {
  const temp = record.fileList.find((item) => item.fileUrl === flieUrl)
  if (temp) {
    downloadByteFile(temp)
  }
}

const exportLoad = ref(false)

async function onExport(type: 'table' | 'template') {
  let fileTitle: string
  exportLoad.value = true
  const headerData = [
    { title: '客户名称', value: 'supplierName', width: 180 },
    { title: '采购单数', value: 'customerAddress', width: 180 },
    { title: '收票日期', value: 'taxNo' },
    { title: '收票金额', value: 'bankAccount' },
    { title: '备注', value: 'payeeAcctBank' },
    { title: '创建时间', value: 'contactName' }
  ]
  let excelData: InvoiceResItem[] = []
  switch (type) {
    case 'table':
      {
        fileTitle = '进项发票数据'
        headerData.unshift({ title: '序号', value: 'index', width: 80 })
        const res = await getInvoiceAllList(searchFrom.value)
        excelData = res.data.list.map((item, index) => {
          item.index = index + 1
          return item
        })
      }
      break
    case 'template':
      fileTitle = '进项发票导入模板'
      excelData = [
        {
          invoiceId: '',
          invoiceCode: '',
          customerId: '',
          supplierName: '',
          invoiceDate: '',
          invoiceAmt: 0,
          invoiceStatus: 0,
          remark: '',
          detailList: [],
          fileList: [],
          invoiceType: 0
        }
      ]
      break

    default:
      break
  }
  import('@renderer/utils/vendor').then((excel) => {
    excel.exportExcel(excelData, headerData, fileTitle)
    exportLoad.value = false
  })
}
</script>
<style lang="less" scoped>
.erp-search-btn-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
